﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KPIS.GERP.Models;
using KPIS.GERP.Models.SYS;
using KPIS.GERP.Models.SYS.ViewModel;
using KPIS.GERP.WEB.GIMS.Class;
using System.Data.Entity;

namespace KPIS.GERP.WEB.GIMS.Controllers
{
    // [AccessDeniedAuthorize]
    public class TaskController : Controller
    { 
        public ActionResult Index(int selectedCategory = 1, bool nolayout = false, bool emptylayout = false)
        {
            ViewBag.NoLayout = nolayout|| emptylayout;
            ViewBag.SelectedCategory = selectedCategory;
            return View();
        }

        public ActionResult Details(int id = 0, int taskHistoryId= 0, int selectedCategory = 1, bool nolayout = false, bool emptylayout = false,
            string commandActionResult = null, string commandActionErrorResult = null, bool hideShowAll = false )
        {
            var context = new GERPContext(true);
            Task task = null;

            
            if(id == 0 && taskHistoryId != 0)
            {
                var th = context.TaskHistories
                    .Include(o => o.Task.ApproveProcess)
                    // .Include(o => o.Task.Simulates.Select(o2 => o2.ApproverPosition))
                    .Include(o => o.Task.Simulates.Select(o2 => o2.ApprovePath))
                    .FirstOrDefault(o => o.TaskHistoryId == taskHistoryId);
                task = th == null || th.Task == null ? null : th.Task;
            } else if(id != 0)
            {
                task = context.Tasks
                    .Include(o => o.ApproveProcess)
                    //.Include(o => o.Simulates.Select(o2 => o2.ApproverPosition))
                    .Include(o => o.Simulates.Select(o2 => o2.ApprovePath))
                    .Include(o => o.TaskHistories) 
                    .FirstOrDefault(o => o.TaskId == id);
            }

            if (task != null && task.Simulates != null && task.Simulates.Any())
            {
                var poses = context.Positions.ToList();//o => o.PosId == s.ApproverPosId);
                foreach (var sim1 in task.Simulates)
                {
                    sim1.ApproverPosition = poses.FirstOrDefault(o => o.PosId == sim1.ApproverPosId);
                }

                if(task.TaskHistories.Any())
                    foreach (var taskHistory1 in task.TaskHistories)
                    {
                        taskHistory1.ApprovePathSimulate.ApproverPosition = 
                            poses.FirstOrDefault(o => o.PosId == taskHistory1.ApprovePathSimulate.ApproverPosId);
                    }
            }
             
            // 0 = ยังไม่ได้ทำอะไร, 1 = สถานะนี้เลิกใช้แล้ว, 2 มีการตอบกลับหรืออนุมัติหรือไม่ผ่านการอนุมัติ โดยมีการสร้าง message_reply ที่อ้างถึง from send seq นั้น
            //if(task != null && task.CurrentTaskHistoryId != null)
            //{
            //    var ms = context.MessageSends.FirstOrDefault(o => o.RecordStatus != "D" && o.RefType == "sys_task" && o.RefId == task.CurrentTaskHistoryId);
            //    if(ms != null)
            //    {
            //        ms.MessageStatus = "0";
            //        context.SaveChanges();
            //    }
            //}

            ViewBag.NoLayout = nolayout || emptylayout;
            ViewBag.SelectedCategory = selectedCategory;
            ViewBag.TaskId = id;
            ViewBag.CommandActionResult = commandActionResult;
            ViewBag.CommandActionErrorResult = commandActionErrorResult;
            ViewBag.HideShowAll = hideShowAll; 
            return View(task);
        }

        public ActionResult FindDetails(int appPrcGrpId, int refId, bool nolayout = false, bool emptylayout = false)
        {
            var context = new GERPContext(true);

            var t = context.Tasks.FirstOrDefault(o => o.RecordStatus != "D" && o.RefId == refId && o.ApproveProcess.ApproveProcessGroup.AppPrcGrpId == appPrcGrpId);
            if(refId != 0 && appPrcGrpId != 0 && t != null)
            {
                return RedirectToAction("Details", new
                    {
                        id = t.TaskId,
                        Nolayout = nolayout || emptylayout
                    });
            }

            return Content("ยังไม่มีคำขออนุมัติ");
        }

        public ActionResult Edit(int id, int selectedCategory = 1, bool nolayout = false, bool emptylayout = false)
        {
            ViewBag.NoLayout = nolayout || emptylayout;
            ViewBag.SelectedCategory = selectedCategory;
            ViewBag.TaskId = id;
            return View();
        }

        public ActionResult Delete(int id, int selectedCategory = 1, bool nolayout = false, bool emptylayout = false)
        {
            ViewBag.NoLayout = nolayout|| emptylayout;
            ViewBag.SelectedCategory = selectedCategory;
            ViewBag.TaskId = id;
            return RedirectToAction("Index", new
                {
                    selectedCategory,
                    NoLayout = nolayout || emptylayout

                });
        }

        [HttpPost]
        public ActionResult TakeAction(FormCollection c, int taskHistoryId, string title, string remarks, int taskId, 
            CommandAction? action = null, bool nolayout = false, bool emptylayout = false)
        {
            string sss = "";
            foreach (var fff in c.AllKeys)
            {
                sss += fff + ">" + c[fff];
            }
            if(!string.IsNullOrWhiteSpace(ModelError(remarks, title, action)))
            {
                return RedirectToAction("Details", new
                    {
                        id = new GERPContext().TaskHistories.FirstOrDefault(o => o.TaskHistoryId == taskHistoryId).TaskId,
                        Nolayout = nolayout|| emptylayout,
                        CommandActionErrorResult = ModelError(remarks, title, action)
                    });
            }

            ViewBag.NoLayout = nolayout || emptylayout;
            ActionTaskVM actionTask = new ActionTaskVM();
            actionTask.TaskHistoryId = taskHistoryId;
            actionTask.ByEmpId = GimsMembership.CurrentEmpId; 
            actionTask.CommandAction = action.Value;
            actionTask.NewTitle = title;
            actionTask.Remarks = remarks;
            actionTask.TaskId = taskId;
            actionTask = new SysApprovalService.SysApprovalServiceClient().ActionTask(actionTask);

            return RedirectToAction("Details", new
                {
                    id = new GERPContext().TaskHistories.FirstOrDefault(o => o.TaskHistoryId == taskHistoryId).TaskId,
                    Nolayout = nolayout || emptylayout,
                    CommandActionResult = actionTask.CommandActionResult,
                    CommandActionErrorResult = actionTask.CommandActionErrorResult
                });
        }

        // [AllowAnonymous]
        public ActionResult ApprovePath()
        {
            return View();
        }

        public string ModelError(string remarks, string title, CommandAction? action = null)
        {
            if(!action.HasValue)
                return "กรุณาเลือกคำสั่งที่ต้องการ";

            else if((CommandAction.Reject == action|| CommandAction.SendBack == action || CommandAction.Cancel == action) && 
            (string.IsNullOrWhiteSpace(remarks)))
                return "กรุณากรอกช่องหมายเหตุ";

            else if(string.IsNullOrWhiteSpace(title))

                return "กรุณากรอกหัวข้อคำขอ";

            return null;
        }
    }
}